const { Transform } = require("stream");
const fs = require("fs");
const moment = require("moment");
const _ = require("lodash");
const utils = require('../../utils');

module.exports = function (file, { inFormat, begin, end } = {}) {
  const stream = new Transform({ objectMode: true });
  inFormat = utils.parseFunction(inFormat);
  file = utils.parseFunction(file);
  let fd;
  if (_.isString(file)) {
    fd = fs.openSync(file, 'w');
    begin && fs.writeSync(fd, `${begin}\n`);
  }
  stream._transform = function (chunk, encoding, callback) {
    utils.debug('fileWriter [chunk]:', chunk);
    stream.push(chunk);
    const line = inFormat ? inFormat(chunk, { _, moment, utils }) : JSON.stringify(chunk);
    if (fd) {
      fs.write(fd, line, callback);
    } else {
      const fileName = file(chunk, { _, moment, utils });
      fs.writeFileSync(fileName, `${begin||''}${line}${end||''}`);
      callback();
    }
  };

  stream.on('finish', function () {
    if (!fd) {
      return utils.debug('fileWriter [finish]:');
    }
    end && fs.writeSync(fd, end);
    fs.close(fd);
    utils.debug('fileWriter [finish]');
  });

  return stream;
};